package com.moonlight.demo.custom;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CustomDecoder extends CumulativeProtocolDecoder {
	private final static Logger logger = LoggerFactory.getLogger(CustomDecoder.class);

	private Charset charset;

	public CustomDecoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
		if(in == null) {
			logger.info("缓冲流为空");
			return false;
		}
		in.mark();
		int len = in.getInt();
		if(in.remaining() - 1 < len - 5) {
			in.reset();
			logger.error("出现差包错误");
			return false;
		}
		in.reset();
		byte[] bytes = new byte[len];
		in.get(bytes , 0 , len);
		byte type = bytes[4];
		String content = new String(bytes , 5 , len - 5 , charset);
		CustomPackage result = new CustomPackage(type, content);
		out.write(result);
		// 查看是否存在粘包情况，如果粘包则继续解析
		return in.remaining() > 0;
	}

}
